import { HttpService } from './../../base/services/http.service';
import { CheckLogin } from './../../base/decorator/login.decorator';
// import { QiniuService } from '../../common/services/qiniu.service';

import { Controller, Post, Body, Get, Query, HttpServer } from '@nestjs/common';
import { WxliteService } from './wxlite.service';
import { WxliteTokenStorage, WxTokenStorage } from './wx.token';

import * as randomstring from 'randomstring';
import { WxSignService } from './wx.sign.service';
import { wxLiteConfig, wxConfig } from './wx.definition';

import { globalError } from 'src/base/interceptors/httpResult.interceptor';
const SHA1 = require('jshashes').SHA1;
@Controller('/wxlite')
export class WxliteController {
    constructor(
        private wxliteService: WxliteService,
        private wxTokenStorage: WxTokenStorage,
        private http: HttpService,
        private wxSignService: WxSignService,
        private wxliteTokenStorage: WxliteTokenStorage,
        // private qiniuService: QiniuService,
    ) {}

    /**
     * 分析小程序的基本数据
     */
    @Post('/parsedata')
    async parseOpenid(@Body() body) {
        try {
            let info = await this.wxliteService.decryptUserData(
                body.code,
                body.encryptedData,
                body.iv,
            );
            return info;
        } catch (e) {
            console.log('=====wxlite=====');
            console.log(e);
            console.log('=====wxlite=====');
            return globalError('操作失败，请重新点击授权');
        }
    }

    @Post('/sign')
    async jsapiSign(@Body('url') url) {
        const token = await this.wxTokenStorage.genToken();
        let jsapi = await this.http.get(
            `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi&offset_type=1`,
        );

        // let ticket: string = JSON.parse(jsapi).ticket;
        let ticket: string = jsapi.ticket;
        let params: any = {
            noncestr: randomstring.generate({ length: 20 }),
            jsapi_ticket: ticket,
            timestamp: parseInt(<any>(Date.now() / 1000)),
            url: url,
        };
        let temp = this.wxSignService.genSortUrl(params);
        params.sign = new SHA1().hex(temp);
        params.appId = wxConfig.app_id;
        return params;
    }

    @Post('/qrcode/token')
    async qrcodeToken(@CheckLogin() uid: string) {
        return await this.wxliteTokenStorage.genToken();
    }
}
